<template>
  <div class="ya-box">
    <el-tag
      v-for="(tag, i) in tagArr"
      :key="tag"
      class="mx-1"
      closable
      @close="handleClose(i)"
      size="small"
    >
      <span
        contenteditable="true"
        @keydown.enter="handleForbiteLine"
        ref="tags"
        >{{ tag }}</span
      >
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="InputRef"
      v-model.trim="inputValue"
      class="ml-1 w-20"
      size="small"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <ya-button v-else size="small" @click="showInput"> + </ya-button>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, defineProps, defineEmits,defineExpose, withDefaults } from "vue";
import { ElTag, ElInput } from "element-plus";
interface PropType {
  modelValue: Array<string>,
  tag: Array<string>,
}
const emit = defineEmits(["tabChange", 'update:modelValue']);
const tags = ref();
const tagArr = ref([]);// 标签值
const { tag = [], modelValue = [] } = defineProps<PropType>()
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();
//删除按钮的事件
const handleClose = (index: number) => {
  tagArr.value.splice(index, 1)
  emit("update:modelValue", tagArr.value);
};
//添加按钮的点击事件
const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};
//enter键禁止换行
const handleForbiteLine = (e) => {
  if (e.code === "Enter") {
    e.preventDefault();
  }
};
//添加的input框失去焦点
const handleInputConfirm = () => {
  if (inputValue.value) {
    tags?.push(inputValue.value);
    addEventListener( tags.value[tags.value.length-1],tags.value.length-1)
    emit("tabChange", tags.value);
  }
  inputVisible.value = false;
  inputValue.value = "";    
};
//增加事件监听
const addEventListener=(data,i)=>{
  data.addEventListener("blur", function (event) {
        const content = event.target.textContent;
        tagArr.value[i] = content;
        emit("update:modelValue", tagArr.value);
      });
}
watchOnce(
  () => tag,
  (val) => {
    tagArr.value = val;
    nextTick(() => {
      tags.value?.forEach((item, i) => {
        addEventListener(item,i)
    });
    })
  },
  {
    deep: true,
  }
);

onMounted(() => {

  
});
// onUnmounted(() => {
//   tags.value?.forEach((item, i) => {
//     item.removeEventListener("blur", function () {});
//   });
// });
// defineExpose({
//   tags,
// })
</script>
<style lang="scss" scoped>
.ya-box {
  .el-tag {
    margin-right: 12px;
    cursor: pointer;
  }
  .el-tag__content {
    span {
      outline: none;
    }
  }
}
</style>
